// 导入发送邮件的方法
const emailSender = require('./sendEmil');
// 导入邮件的配置
const config = require('./index');
// 导入已封装的数据函数
const db = require('../db/db');
// 把验证码储存在数据库
class EmailService {
    static delay = null;
    static EXPIRE_TIME = 60 * 1000; // 验证码过期时间：60秒

    // 发送邮件 client_email: 用户邮箱
    static async getEmailCode(clientEmail, mailType = config.defaultMailType) {
        try {
            // 使用参数化查询，传入参数数组
            const existingCode = await db.query(
                'SELECT * FROM pre_email WHERE email = ?', 
                [clientEmail]  // 参数作为数组传入
            );

            if (existingCode.length >= 1) {
                return {
                    code: 1,
                    msg: '已发送验证码,请勿重复发送。60秒后重新发送。'
                };
            }

            // 发送新验证码
            const result = await emailSender.sendVerifyCode(
                clientEmail,
                mailType,
                config.projectName
            );

            if (!result.success) {
                throw new Error(result.error);
            }

            // 存储验证码
            await this.writeEmailCode(clientEmail, result.code);

            // 设置验证码过期定时器
            if (this.delay) {
                clearTimeout(this.delay);
            }

            this.delay = setTimeout(async () => {
                await this.removeEmailCode(clientEmail);
                this.delay = null;
            }, this.EXPIRE_TIME);

            return {
                code: 200,
                msg: '发送验证码成功,请注意60秒后验证码过期'
            };

        } catch (error) {
            console.error('发送验证码错误:', error);
            return {
                code: -1,
                msg: '发送验证码失败',
                error: error.message
            };
        }
    }
    
    // 添加验证码 (把验证码存储在数据库)
    static async writeEmailCode(clientEmail, code) {
        try {
            await db.query(
                'INSERT INTO pre_email(email, vcode) VALUES(?, ?)',
                [clientEmail, code]  // 多个参数都放在数组中
            );
            return { code: 200, msg: '添加验证码成功' };
        } catch (error) {
            throw new Error('存储验证码失败: ' + error.message);
        }
    }

    // 删除验证码
    static async removeEmailCode(clientEmail) {
        try {
            await db.query(
                'DELETE FROM pre_email WHERE email = ?',
                [clientEmail]
            );
            return { code: 200, msg: '删除验证码成功' };
        } catch (error) {
            console.error('删除验证码失败:', error);
            return { code: -1, msg: '删除验证码失败' };
        }
    }

    // 校验邮件验证码
    static async verifyEmailCode(clientEmail, code) {
        try {
            const rows = await db.query(
                'SELECT * FROM pre_email WHERE email = ? AND vcode = ?',
                [clientEmail, code]
            );

            if (rows.length === 1) {
                // 验证成功后删除验证码
                await this.removeEmailCode(clientEmail);
                return { code: 200, msg: '邮箱验证成功' };
            }

            return { code: -1, msg: '验证码错误或已过期' };
        } catch (error) {
            console.error('验证码校验失败:', error);
            return { 
                code: 500, 
                msg: '邮箱验证失败，服务端异常',
                error: error.message 
            };
        }
    }
}
module.exports = EmailService;